(function(pageName){
  sugarcane.module[pageName] = function(){
    $('.j-pagescreen').addClass('fn-hide');
    var urlParams = sugarcane.getUrlParams(),
      docType = 2,
      //newsId = urlParams['newsId'],
      id = urlParams['id'];
    if ($('#j-screen-'+pageName+id).length) {
      var pageScreen = $('#j-screen-'+pageName+id);
      pageScreen.removeClass('fn-hide');
      var _scrollTop = pageScreen.data('scrolltop') || 0;
      setTimeout(function(){
        $(window).scrollTop(_scrollTop);
      }, 10);
      return false;
    }
    var pageScreen = $('<div class="j-pagescreen j-pagescreen-detail" id="j-screen-'+pageName+id+'"></div>');
    $('body').append(pageScreen);

    detailShow();

    // 获取新闻
    var detailData = {};
    function detailShow(){
      if (id) {
        sugarcane.ajaxApi({
          "url": "/newspaper/detail",
          "data": {"id": id},
          "callback": function(res){
            if (res['code'] == 0) {
              detailData = res['data'];
              sugarcane.twoShare({
                "id": res.data.id,
                "title": res.data.title,
                "desc": '分享来自经济日报客户端，更多精彩请下载http://d.jingjiribao.cn/index.html',
                "imgUrl": res.data.shareImage,
                "link": res.data.shareUrl,
                "docType": res.data.docType
              });
              if(res.data.docType){
                docType = res.data.docType;
              }
              //document.title = detailData['title'];
              // 引用标题
              if (detailData['referTitle']) pageScreen.append(newGrapes["subtitle"].init({"title":detailData['referTitle']}));
              // 标题
              pageScreen.append(newGrapes["newstitle"].init({"title":detailData['title']}));
              // 副标题
              if (detailData['subTitle']) pageScreen.append(newGrapes["subtitle"].init({"title":detailData['subTitle']}));
              // 发布时间 && 语音播报
              var readnewsHtml = '';
              if (!sugarcane['app']['isShare'] && detailData['content'] && detailData['voicebroadcast']) {
                readnewsHtml = '<div class="app-readnews"></div>';
              }
              pageScreen.append(newGrapes["newstime"].init({"sub1":detailData['period'],"sub2":detailData['author'],"sub3":"","subright1":readnewsHtml,"subright2":"","subright3":""}));

              // 内容
              if (detailData['content']) {
                var newscontentObj = newGrapes["newscontent"].init({"content":detailData['content']});
                // 处理编辑携带的字体大小
                // newscontentObj.find('*').css("font-size", "inherit");
                
                // 处理编辑携带的字体大小，按屏幕大小等比显示，还有行高
                newscontentObj.find('*').each(function(){
                  var _fontSize = this.style.fontSize,
                    _lineHeight = this.style.lineHeight;
                  if (_fontSize) {
                    _fontSize = _fontSize.toLowerCase();
                    if (_fontSize.indexOf('px') > -1) {
                      _fontSize = (_fontSize.replace('px', '') * pageScreen.width() / 375) + 'px';
                      $(this).css('font-size', _fontSize);
                    }
                  }
                  if (_lineHeight) {
                    _lineHeight = _lineHeight.toLowerCase();
                    if (_lineHeight.indexOf('px') > -1) {
                      _lineHeight = (_lineHeight.replace('px', '') * pageScreen.width() / 375) + 'px';
                      $(this).css('line-height', _lineHeight);
                    }
                  }
                });
                // 处理图片大小
                newscontentObj.find('img').each(function(){
                  var _this = this;
                  var _width = $(this).attr('width'),
                    _height = $(this).attr('height');
                  if (_width) {
                    _width = _width.replace('px', '') * pageScreen.width() / 375;
                    $(this).attr('width', _width);
                  }
                  if (_height) {
                    _height = _height.replace('px', '') * pageScreen.width() / 375;
                    $(this).attr('width', _height);
                  }
                  if(!_width && !_height){
                    //如果图片没有任何样式，以像素来显示
                    var newImage = new Image();
                    newImage.src = $(this).attr('src');
                    if (newImage.complete) { 
                      var _width = newImage.width,
                        _height = newImage.height;
                      _width = _width * pageScreen.width() / 375;
                      $(_this).css('width', _width);
                      $(_this).css('max-width', '100%').css('display','block');
                    }else{
                      newImage.onload = function(){
                        var _width = this.width,
                          _height = this.height;
                        _width = _width * pageScreen.width() / 375;
                        $(_this).css('width', _width);
                        $(_this).css('max-width', '100%').css('display','block');
                      }
                    }
                  }
                });

                // 设置字体大小
                pageScreen.addClass('app-fontsize-' + sugarcane['app']['fontSize']);

                pageScreen.append(newscontentObj);


                if (!sugarcane['app']['isShare']) {
                  formatContent(newscontentObj);
                }

                // 语音播报
                if (!sugarcane['app']['isShare']) {

                  var voiceContent = newscontentObj.find('.news-content').text(),
                    _this = null,//保存点击的语音播报按钮 
                    voiceState = null;
                  pageScreen.find('.app-readnews').on(tap, function(){
                    _this = this;
                    if (voiceState == 'play') {
                      peach.readNewsPaused();
                    } else if(voiceState == 'pause'){
                      peach.readNewsPlay();
                    } else{
                      peach.readNews(voiceContent);
                    }
                  });

                  peach.readNewsStatus(function(param){
                    if(param['status'] == 'playing'){
                      $(_this).addClass('pause');
                      //更改按钮交互
                      voiceState = 'play';
                    }else if(param['status'] == 'paused'){
                      voiceState = 'pause';
                      $(_this).removeClass('pause');
                    }else if(param['status'] == 'stop'){
                      voiceState = 'stop';
                    }
                  });

                  peach.readNewsError(function(){
                    peach.toast('播放失败');
                    voiceState = null;
                    $(_this).removeClass('pause');
                  });
                  peach.readNewsEnd(function(){
                    voiceState = null;
                    $(_this).removeClass('pause');
                  });
                
                }

              }
              // shareBanner();
              sugarcane['shareBanner']({
                //'newsId': newsId,
                'id': id,
                'docType': docType,
                'containObj': pageScreen 
              });
            } else {
              showerrorView();
              peach.hiddenAppbar()
              // alert(res['message']);
            }
          }
        });
      }
    }
    function formatPoster(poster, width, height, callback){
      var newImg = new Image();
      newImg.src = poster;
      if (newImg.complete) {
        if ((width / height) > (newImg.width / newImg.height)) {
          newImg.style.height = height;
        } else {
          var _height = width * newImg.height / newImg.width;
          newImg.style.width = width;
          newImg.style.marginTop = (height - _format['height']) / 2;
        }
        callback(newImg);
        // newObj.find('.poster').html(newImg);
      } else {
        newImg.onload = function () {
          if ((width / height) > (newImg.width / newImg.height)) {
            newImg.style.height = height;
          } else {
            var _height = width * newImg.height / newImg.width;
            newImg.style.width = width;
            newImg.style.marginTop = (height - _format['height']) / 2;
          }
          callback(newImg);
          // newObj.find('.poster').html(newImg);
        };
        newImg.onerror = function (error) {
          // console.log(error);
        };
      }
    }
    // 处理内容
    function formatContent(contentObj){
      // 处理 a 标签
      contentObj.find('a').each(function(){
        $(this).data('href', $(this).attr('href'));
        $(this).attr('href','javascript:void(0)');
        $(this).on(tap, function(){
          peach.openUrl($(this).data('href'));
        });
      });
      // 处理 img 标签
      var imgList = [];
      contentObj.find('img').each(function(index){
        $(this).data('index', index);
        imgList.push({'imgUrl': $(this).attr('src'),'imgTitle': $(this).attr('title') || $(this).attr('alt') || ''});
      });
      contentObj.find('img').on(tap, function(){
        peach.previewImage({
          'index': $(this).data('index'),
          'imgList': imgList
        });
      });
      // 处理 video 标签
      contentObj.find('video').each(function(){
        var newObj = $('<div><div class="play"></div><div class="poster"></div></div>');
        if ($(this).hasClass('vr-video') || $(this).hasClass('vr')) {
          newObj.addClass('app-vr');
        } else {
          newObj.addClass('app-video');
        }
        var width = $(this).width(),
          height = $(this).height(),
          poster = $(this).attr('poster') || '';
        newObj.width(width);
        newObj.height(height);
        newObj.data('poster', poster);
        newObj.data('src', $(this).attr('src') || '');
        $(this).before(newObj);
        $(this).remove();
        // poster
        if (poster) {
          formatPoster(poster, width, height, function(posterImg){
            newObj.find('.poster').html(posterImg);
          });
        }
      });
      contentObj.find('.app-vr').on(tap, function(){
        peach.playVrFull($(this).data('src'));
      });
      contentObj.find('.app-video').on(tap, function(){
        var offset = $(this).offset();
        peach.playVideo({
          'url': $(this).data('src'),
          'poster': $(this).data('poster'),
          'offsetX': offset['left'],
          'offsetY': offset['top'],
          'width': offset['width'],
          'height': offset['height']
        });
      });
    }

    // function shareBanner(){
    //   if(sugarcane['app']['isShare'] && !pageScreen.find('.app-banner').length ){
    //     sugarcane.module.load('banner', function(listitemFn){
    //       var bannerObj = listitemFn({'id': id, 'docType': docType});
    //       pageScreen.append(bannerObj);
    //       var _height = $(bannerObj).css('height');
    //       pageScreen.css('margin-bottom',_height);
    //     });
    //   }
    // }

    function showerrorView(){
      var clientHeight = document.documentElement.clientHeight;
      pageScreen.css('position','relative').css('height',clientHeight+'px');
      var errorviewObj = $(`<div class="app-errorview">
          <img class="img" src="/static/img/isempty.png">
        <p class="error-tip">暂时没有数据</p>
      </div>`);
       pageScreen.append(errorviewObj);
    }
  }

  sugarcane.module['state'][pageName] = 'load';
  sugarcane.module.callback(pageName);
}('readnews'));
